package com.xiao.androidcompose01.weight

import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextMotion
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.xiao.androidcompose01.ui.theme.MainColor
import kotlin.math.cos
import kotlin.math.sin
import kotlin.text.ifEmpty


@Composable
fun PhoneInputField(hint:String, onChange: (String) -> Unit, modifier: Modifier = Modifier) {
   val phone = remember { mutableStateOf("")}
   var hintText by remember { mutableStateOf(hint) }
   var inputHasFocus by remember { mutableStateOf(false) }
   val focusRequest by remember { mutableStateOf(FocusRequester()) }
   BasicTextField(value = phone.value.ifEmpty { hintText },
      onValueChange = {
         if (it.length<=11){
            phone.value = it
            onChange(it)
         }
      }, singleLine = true,
      keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone),
      cursorBrush = Brush.linearGradient(listOf(MainColor, MainColor)),
      textStyle = TextStyle(fontSize = 16.sp, textMotion = TextMotion.Static, color = if (phone.value.isBlank())Color(0xFF999999) else MainColor),
      decorationBox = { innerTextField ->
         Row(modifier = Modifier.fillMaxWidth()) {
            Row(modifier = Modifier.weight(1f)) {
               innerTextField()
            }
            Icon(Icons.Default.Close,null, tint = MainColor, modifier = Modifier
               .alpha(
                  if (phone.value.isEmpty()) 0f else 1f
               )
               .click(phone.value.isNotEmpty()) {
                  focusRequest.requestFocus()
                  phone.value = ""
                  onChange("")
               })
         }
      },
      modifier = modifier
         .focusRequester(focusRequest)
         .border(1.dp, color = MainColor, shape = RoundedCornerShape(5.dp))
         .padding(vertical = 12.dp, horizontal = 12.dp)
         .onFocusChanged {
            inputHasFocus = it.isFocused
            hintText = if (!it.isFocused) {
               hint
            } else {
               ""
            }
         })
}


@Composable
fun PasswordInputField(hint: String, onChange:(String)-> Unit, modifier: Modifier = Modifier) {
   var password by remember { mutableStateOf("") }
   var hintText by remember { mutableStateOf(hint) }
   var inputHasFocus by remember { mutableStateOf(false) }
   val focusRequest by remember { mutableStateOf(FocusRequester()) }
   BasicTextField(value = password.ifEmpty { hintText },
      onValueChange = {
         if (it.length<=16){
            password = it
            onChange(it)
         }
      },
      
      visualTransformation = if (password.isBlank()) VisualTransformation.None else PasswordVisualTransformation(),
      decorationBox = { innerTextField ->
         Row(modifier = Modifier.fillMaxWidth()) {
            Row(modifier = Modifier.weight(1f)) {
               innerTextField()
            }
            Icon(Icons.Default.Close,null, tint = MainColor, modifier = Modifier
               .alpha(
                  if (password.isEmpty()) 0f else 1f
               )
               .click(password.isNotEmpty()) {
                  password = ""
                  focusRequest.requestFocus()
                  onChange("")
               })
         }
      }, singleLine = true,
      keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
      cursorBrush = Brush.linearGradient(listOf(MainColor, MainColor)),
      textStyle = TextStyle(fontSize = 16.sp, textMotion = TextMotion.Static, color = if (password.isBlank())Color(0xFF999999) else MainColor),
      modifier = modifier
         .focusRequester(focusRequest)
         .border(
            1.dp,
            color = if (password.isEmpty()) Color(0xFFCCCCCC) else MainColor,
            shape = RoundedCornerShape(5.dp)
         )
         .padding(vertical = 12.dp, horizontal = 12.dp)
         .onFocusChanged {
            inputHasFocus = it.isFocused
            hintText = if (!it.isFocused) {
               hint
            } else {
               ""
            }
         })
}

enum class MainButtonState{
   ENABLE,
   LOADING,
   DISABLE
}

/**
 * -1 禁用
 * 0： 加载中
 * 1: 默认
 */
@Composable
fun MainButton(text:String,state:MainButtonState = MainButtonState.ENABLE, modifier: Modifier = Modifier, onClick:()->Unit) {
   var color = MainColor
   var enable = false
   var isLoading = false
   when(state){
      MainButtonState.ENABLE -> {
         enable = true
         color = MainColor
         isLoading = false
      }
      MainButtonState.LOADING -> {
         enable = false
         color = Color(0xFFCCCCCC)
         isLoading = true
      }
      MainButtonState.DISABLE -> {
         enable = false
         color = Color(0xFFCCCCCC)
         isLoading = false
      }
   }
//    val color = if (enable) MainColor else Color(0xFFCCCCCC)
   Box(modifier
      .background(color, RoundedCornerShape(20.dp))
      .padding(horizontal = 8.dp, vertical = 12.dp)
      .click(enable, onClick),
   ){
      LoadingAnim(modifier = Modifier
         .size(20.dp)
         .alpha(if (isLoading) 1f else 0f))
      Text(text, fontSize = 14.sp, color = Color.White, modifier = Modifier.align(Alignment.Center))
      
   }
}

@Composable
fun OperateButton(modifier: Modifier = Modifier,text:String,enable: Boolean,onClick: () -> Unit) {
   val bg = if (enable) Color(0xFF43912A) else Color(0xFFCCCCCC)
   Box(modifier
      .background(bg, RoundedCornerShape(20.dp))
      .padding(horizontal = 12.dp, vertical = 5.dp)
      .click(enable,onClick),
   ){
//      LoadingAnim(modifier = Modifier
//         .size(20.dp)
//         .alpha(if (isLoading) 1f else 0f))
      Text(text, fontSize = 14.sp, color = Color.White, modifier = Modifier.align(Alignment.Center))
      
   }
}

@Preview
@Composable
private fun OperateButtonPreview() {
   OperateButton(text = "查看屏幕", enable = false){
   
   }
}

@Composable
fun LoadingAnim(modifier: Modifier = Modifier) {
   // 角度动画：0 到 360 度无限循环
   
   val angle by rememberInfiniteTransition().animateFloat(
      initialValue = 0f,
      targetValue = 360f,
      animationSpec = infiniteRepeatable(
         animation = tween(durationMillis = 4000, easing = LinearEasing),
         repeatMode = RepeatMode.Restart
      )
   )
   Box(modifier.drawWithContent {
      drawCircle(
         color = Color.Red,
         radius = size.height.div(2f),
         center = center
      )
      val pointRadius = size.height.div(15f)
      val radius = size.height.div(2f)-pointRadius.times(2)
      val centerX = center.x
      val centerY = center.y
      // 计算小圆点的位置
      val x = centerX + radius * cos(Math.toRadians(angle.toDouble())).toFloat()
      val y = centerY + radius * sin(Math.toRadians(angle.toDouble())).toFloat()
      drawCircle(
         color = Color.White,
         radius = pointRadius, // 小圆点大小
         center = Offset(x, y)
      )
      drawContent()
   })
}


@Preview(showBackground = true)
@Composable
private fun InputSinglePreview() {
   Column(modifier = Modifier.fillMaxWidth()) {
      PhoneInputField(
         hint = "请输入手机号",
         onChange = {},
         modifier = Modifier.fillMaxWidth()
      )
      PasswordInputField(hint = "请输入密码",  onChange = {}, modifier = Modifier
         .padding(top = 8.dp)
         .fillMaxWidth())
      MainButton(text = "登录", state = MainButtonState.ENABLE){
      
      }
   }
//    InputSingle(modifier = Modifier,paddingValues = PaddingValues(horizontal = 12.dp, vertical = 20.dp), input = input)

}

@Preview
@Composable
private fun LoadingAnimPreview() {
   MainButton(modifier = Modifier.fillMaxWidth(), text = "登录",
      state = MainButtonState.LOADING){
      
   }
//    LoadingAnim(modifier = Modifier.size(80.dp,80.dp))
}
